<template>
  <div class="app-container">
    <div style="margin-top: 15px;" class="app-header">
      <div class="header-left">
        <div class="search-title">名称/型号</div>
        <el-input placeholder="请输入搜索内容" class="search-input" v-model="keyword" @keyup.enter.native="handleEnter">
          <template slot="append">
            <el-button slot="append" icon="el-icon-search" @click.native="searchBtn"></el-button>
          </template>
        </el-input>
      </div>
      <div class="header-right">
        <el-button type="primary" class="header-btn-one" @click.native="cancle">取消</el-button>
        <el-button type="success" class="header-btn-two" @click="createDiscount">保存</el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      ref="elTable"
    >   
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{scope.$index + (paginationIndex - 1) * 15 + 1}}
        </template>
      </el-table-column>
      <el-table-column label="编号" width="150">
        <template slot-scope="scope">
          {{scope.row.number}}
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center">
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column label="库存" width="150" align="center">
        <template slot-scope="scope">
          {{scope.row.count}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="价格" width="150" align="center">
        <template slot-scope="scope">
          {{scope.row.price}}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="编辑折扣" width="300">
        <template slot-scope="scope">
          <el-input placeholder="请输入内容" v-model="scope.row.discount" @blur="handleBlur(scope)"></el-input>
        </template>
      </el-table-column>
    </el-table>
    <Pagination @submit="handleSubmit" :total="total" class="pagination"></Pagination>
  </div>
</template>
<script>
import { getList, getDiscountList } from "@/api/table"
import {createDiscount} from '@/api/operations'
import Pagination from '@/views/pagination/pagination'
import { Message } from 'element-ui'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "gray",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      listLoading: true,
      paginationIndex: 1,
      total: 0,
      page: 1,
      list: [],
      discountList: [],
      keyword: '',
      searchList: [],
      paramsId: {},
      storageList: {},
      PARAMS: {}
    };
  },
  methods: {
    handleEnter() {
      this.searchBtn()
    },
    searchBtn() {
      this.list = []
      this.page = 1
      this.paginationIndex = 1
      this.total = 0

      let params
      if (!this.keyword) {
        params = Object.assign({}, {page: this.page})
      } else {
        params = Object.assign({}, {page: this.page, keyword: this.keyword})
      }
      this._searchResult(params)
    },
    handleBlur(scope) {
      let reg1 = /^[0-9]+\.[0-9]+$/
      let reg2 = /^[0-9]+$/
      // if (scope.row.discount === '') return
      // console.log(scope)
      if (!reg1.test(scope.row.discount) && !reg2.test(scope.row.discount)) {
        Message({
          message: '请输入整数或小数',
          type: 'warning',
          duration: 2000
        })
        return
      }
      let obj = Object.assign({}, {part_id: scope.row.id, discount: scope.row.discount})
      if (this.discountList.length !== 0) {
        let index = this.discountList.findIndex((item) => {
          return item.part_id === scope.row.id
        })
        if (index >= 0) {
          this.discountList.splice(index, 1)
        }
      }
      this.discountList.push(obj)
      this.PARAMS = Object.assign({}, {user_id: this.$route.params.id}, {list:JSON.stringify(this.discountList)})
    },
    createDiscount() {
      createDiscount(this.PARAMS)
      let store = this.getStorage()
      if (store === null || !store.hasOwnProperty('list')) {
        this.setStorage(this.PARAMS)
      } else {
        let list
        if (typeof(store.list) == 'string') {
          list = JSON.parse(this.getStorage().list)
        } else {
          list = this.getStorage().list
        }
        
        let PARAMS_LIST = JSON.parse(this.PARAMS.list)
        
        PARAMS_LIST.forEach((PARAMS_Item) => {
          let index = list.findIndex((item) => {
            return item.part_id === PARAMS_Item.part_id
          })
          if (index >= 0) {
            list.splice(index, 1)
          }
        })
        
        list = list.concat(PARAMS_LIST)
        
        let res = Object.assign({}, {user_id: this.$route.params.id}, {list})
        this.setStorage(res)
      }
      
      // console.log(this.PARAMS)
      this.$router.push({path: '/client/table'})
    },
    cancle() {
      // this.$emit("cancle")
      this.$router.push({path: '/client/table'})
    },
    handleSubmit(val) {
      this.paginationIndex = val
      if (this.list.length === 0) return
      this.page = val
      // console.log(this.page)
      if (this.searchList.length > 0) {
        let params = Object.assign({}, {page: this.page, keyword: this.keyword})
        this._searchResult(params)
      } else{
        this.fetchData()
      }
    },
    getStorage() {
      let storage = localStorage.getItem(`SET_STORAGE_LIST${this.$route.params.id}`)
      return JSON.parse(storage)
    },
    setStorage(store) {
      localStorage.setItem(`SET_STORAGE_LIST${this.$route.params.id}`, JSON.stringify(store))
    },
    fetchData() {
      this.listLoading = true
      getList(this.page).then(response => {
        if (response.code === 200) {
          this.total = response.data.total
          //给list添加part_id
          let disList = response.data.list
          disList.forEach((item) => {
            item.discount = ''
            //拿到localstorage数据
            if (this.getStorage() !== null) {
              let store
              if (typeof(this.getStorage().list) == 'string') {
                store = JSON.parse(this.getStorage().list)
              } else{
                store = this.getStorage().list
              }
              store.forEach((obj) => {
                if (item.id === obj.part_id) {
                  item.discount = obj.discount
                }
              })
            }
          })
          this.list = disList
          this.listLoading = false
          // console.log( this.list)
        }
      })
    },
    _searchResult(params) {
      getDiscountList(params)
        .then((res) => {
          if (res.code === 200) {
            this.total = res.data.total
            this.searchList = res.data.list
            this.list = this.searchList
            // console.log(this.searchList)
          }
        })
    },
  },
  created() {
    this.fetchData()
  },
  components: {
    Pagination
  }
};
</script>
<style lang="scss" scoped>
.app-container {
  // position: absolute;
  // left: 0;
  // right: 0;
  // top: 0;
  // bottom: 0;
  z-index: 999;
  background: #fff;
}
.el-table /deep/ .cell {
  color: rgb(51, 51, 51);
  font-size: 14px;
  text-align: center;
}
.el-input /deep/ .el-input__inner {
  outline: none;
  border-radius: 12px;
  border: none;
}
.el-table /deep/ .el-row {
  display: flex;
  justify-content: space-between;
}
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 0 !important;
  margin-bottom: 20px;
  .header-left {
    display: flex;
    justify-content: flex-start;
    width: 320px;
    .search-title {
      font-family: SourceHanSansSC;
      font-weight: 400;
      font-size: 14px;
      color: rgb(16, 16, 16);
      font-style: normal;
      letter-spacing: 0px;
      line-height: 20px;
      position: relative;
      top: 10px;
      margin-right: 20px;
      white-space: nowrap;
    }
    .search-input {
      width: 255px;
      height: 32px;
      border-color: rgb(221, 221, 221);
      border-radius: 6px;
      font-size: 14px;
      padding: 0px;
      border-width: 1px;
      border-style: solid;
      text-align: center;
      line-height: 20px;
      font-weight: normal;
      font-style: normal;
      opacity: 1;
      .el-button {
        width: 40px;
        height: 100%;
        background-color: rgb(221, 221, 221);
        border-color: transparent;
        font-size: 14px;
        padding: 0px;
        border-style: solid;
        text-align: center;
        line-height: 20px;
        font-weight: normal;
        font-style: normal;
        opacity: 1;
      }
    }
  }
  .header-right {
    .header-btn-one {
      width: 87px;
      height: 30px;
      background-color: rgb(27, 166, 135);
      border-radius: 6px;
      font-size: 14px;
      padding: 0px;
      border-width: 0px;
      border-style: solid;
      text-align: center;
      line-height: 20px;
      font-weight: normal;
      font-style: normal;
      opacity: 1;
    }
    .header-btn-two {
      width: 87px;
      height: 30px;
      background-color: rgb(27, 166, 135);
      border-radius: 6px;
      font-size: 14px;
      padding: 0px;
      border-width: 0px;
      border-style: solid;
      text-align: center;
      line-height: 20px;
      font-weight: normal;
      font-style: normal;
      opacity: 1;
    }
  }
}
.el-row {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: flex-start;
  .el-button {
    width: 70px;
    height: 34px;
    border-radius: 6px;
    font-size: 14px;
    padding: 0px;
    border-width: 0px;
    border-style: solid;
    text-align: center;
    line-height: 20px;
    font-weight: normal;
    font-style: normal;
    opacity: 1;
    &:nth-child(1) {
      background-color: rgb(27, 166, 135);
    }
    &:nth-child(2) {
      background-color: rgb(90, 152, 222);
    }
    &:nth-child(3) {
      background-color: rgb(59, 57, 78);
    }
  }
}
.el-table {
  // position: absolute;
  // left: 0;
  // right: 0;
  // bottom: -200px;
  // top: 70px;
  overflow: inherit;
  .el-table_1_column_6 {
    width: 200px;
  }
}
</style>
